<template>
	<div class="card-header-box1">
		<el-form ref="queryForm" :inline="true" :model="formParams" :rules="rules">
			<el-form-item prop="dgbzReviewTime" label="评审时间:">
				<el-date-picker
					v-model="formParams.dgbzReviewTime"
					type="date"
					:disabled="!getedit"
					value-format="YYYY-MM-DD HH:mm:ss"
					format="YYYY-MM-DD"
					style="width: 100%"
				/>
			</el-form-item>

			<el-form-item label="阶段状态:" class="ml20">
				<div style="color: #666">
					{{
						props.datainfo.progressColor == 'green' || props.datainfo.progressColor == ''
							? '正常'
							: props.datainfo.progressColor == 'orange' || props.datainfo.progressColor == 'red'
								? '滞后'
								: ''
					}}
				</div>
			</el-form-item>
		</el-form>

		<div class="titlezi flex">
			<div class="flex-1">主编单位</div>
		</div>

		<div class="kuaibj mt20">
			<Cfupload
				v-for="value in fjcodelist"
				:key="value"
				:istable="false"
				:labeltitle="value.definitionName"
				:code="value.businessCode"
				:suffix-type="value.suffixType"
				:disabled="getedit"
				:ismust="value.imustUpload"
				:filelist="value.uploadedFiles"
				@success="handleUploadSuccess"
				@remove="handleFileRemove"
			></Cfupload>

			<Zhuanjiatable :zjtablelist="formParams.outlinePreparationExperts" :isedit="getedit" @getlist="getzjlist" />
		</div>

		<div v-if="backshow" class="dialog-footer mt10">
			<el-button type="primary" plain @click="cancelSubmit()">退回</el-button>
		</div>
		<div v-if="buttonshow" class="dialog-footer mt10">
			<el-button type="success" @click="savezancun">暂存</el-button>
			<el-button type="primary" @click="saveshuju">提交</el-button>
		</div>
	</div>
</template>
<script setup lang="ts">
import { ref, defineProps, watch, nextTick, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Cfupload from '@/components/cf-upload/index.vue'
import { router } from '@/router'
import {
	progressInfoApi,
	basicInfoApi,
	queryFilesSettingApi,
	updateStageAndStatusApi,
	updateProgressApi,
	changeStageAndStatusApi
} from '@/api/bianzhi/index'
import Zhuanjiatable from './zhuanjiatable.vue'

import { useDictionaryStore } from '@/store/modules/dictionary'
import { file } from '@babel/types'
import { get } from 'sortablejs'
const emit = defineEmits<{ (event: 'updateData', value: ''): void }>()
const dictionaryStore = useDictionaryStore()
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()
// const jdstatuslist = dictionaryStore.getDictionaryByCode('T007')
const props = defineProps({
	datainfo: {
		type: Object,
		default: () => ({})
	},
	requestParams: {
		type: Object,
		default: () => ({ outlinePreparationFileList: [] }) //大纲准备阶段 文件列表
	}
})
const queryForm = ref()
const fjcodelist = ref(null)
const datalist = ref([])
const uploadedFiles = ref([])
const formParams = ref({} as any)
const rules = reactive({
	dgbzReviewTime: [{ required: true, message: '请选择时间', trigger: 'change' }]
})

watch(
	() => props.requestParams,
	(newVal: any, oldVal: any) => {
		// console.log(props.datainfo, 'props.datainfo')
		formParams.value = newVal || {}
		//console.log(newVal, 'aa')
		queryFilesSettingApi({ businessStage: 'OutlinePreparation' }).then(res => {
			fjcodelist.value = res.data
			nextTick(() => {
				const fileList = Array.isArray(formParams.value.outlinePreparationFileList) ? formParams.value.outlinePreparationFileList : []
				const arry = [...fileList]
				if (arry.length > 0 && arry) {
					const aa: any = formParams.value.outlinePreparationFileList

					uploadedFiles.value = aa //赋值给 uploadedFiles
					const result = fjcodelist.value.map(itemA => {
						const matchedItem = aa.find(itemB => itemB.remark === itemA.definitionName)
						//	console.log(matchedItem, 'matchedItem')
						if (matchedItem) {
							return { ...itemA, uploadedFiles: [matchedItem] } // 合并相同字段的数据
						}
						return itemA
					})
					fjcodelist.value = result //result赋值给 fjcodelist
				}
			})
		})
	},
	{ immediate: true }
)

const getedit = computed(() => {
	if (props.requestParams.progressStage == '6') {
		if (props.datainfo.edit == 'true') {
			if (userStore.user.roleCode.includes('SB')) {
				return true
			} else {
				return false
			}
		} else {
			return false
		}
	} else {
		return false
	}
})
const backshow = computed(() => {
	if (Number(props.requestParams.progressStage) == 7 && Number(props.requestParams.progressStatus) < 2) {
		if (props.datainfo.edit == 'true' && !userStore.user.roleCode.includes('ZJW')) {
			return true
		} else {
			return false
		}
	} else {
		return false
	}
})

const buttonshow = computed(() => {
	if (Number(props.requestParams.progressStage) == 6) {
		if (props.datainfo.edit == 'true') {
			if (userStore.user.roleCode.includes('SB')) {
				return true
			} else {
				return false
			}
		} else {
			return false
		}
	} else {
		return false
	}
})
onMounted(() => {})

// 处理上传成功事件
const handleUploadSuccess = (data: any) => {
	uploadedFiles.value.push(data) // 将接口返回的数据添加到文件列表
}

// 处理文件删除事件
const handleFileRemove = (file: any) => {
	const id = file.response ? file.response.data.id : file.id
	uploadedFiles.value = uploadedFiles.value.filter(
		item => item.id !== id // 根据 uid 删除对应文件
	)
}
const newadditem = () => {
	const list: any = {
		expertName: '',
		expertTitle: '',
		expertCompany: '',
		expertTel: ''
	}
	datalist.value.push(list)
}
const getzjlist = value => {
	formParams.value.outlinePreparationExperts = value
}
const saveshuju = () => {
	queryForm.value.validate(valid => {
		if (valid) {
			if (!validateBeforeSubmit(fjcodelist.value, uploadedFiles.value)) {
				return
			}
			if (formParams.value.outlinePreparationExperts.length == 0) {
				ElMessage.error('请至少添加一条专家信息')
				return false
			}
			ElMessageBox.confirm('是否确认提交', '确认提交', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					Emittion('SolicitOpinions_Before', 1)
				})
				.catch(() => {})
		} else {
			console.log('error submit!!')
			return false
		}
	})
}

const validateBeforeSubmit = (requiredItems, uploadedFiles) => {
	const errors = []

	requiredItems.forEach(item => {
		const uploadedItem = uploadedFiles.some(file => file.remark === item.definitionName)
		if (!uploadedItem && item.imustUpload === 1) {
			errors.push(`【${item.definitionName}】未上传文件`)
		}
	})

	if (errors.length > 0) {
		ElMessage.error(errors.join(','))
		return false
	}

	return true
}
const savezancun = () => {
	queryForm.value.validate(valid => {
		if (valid) {
			const experlist = formParams.value.outlinePreparationExperts.map((it: any) => ({
				expertName: it.expertName,
				expertTitle: it.expertTitle,
				expertCompany: it.expertCompany,
				expertTel: it.expertTel,
				id: it.id ? it.id : ''
			}))
			//console.log(experlist, 'fsjfdsjfdjdsj')
			const data = {
				expertsList: experlist,
				id: props.requestParams.id,
				standardProjectName: props.requestParams.name,
				standardNumber: props.requestParams.standardNumber,
				dgbzReviewTime: formParams.value.dgbzReviewTime, //大纲评审时间  //大纲评审时间
				zqyjReviewTime: props.requestParams.zqyjReviewTime, //征求意见评审时间
				songsReviewTime: props.requestParams.songsReviewTime, //送审评审时间
				baopCompletionTime: props.requestParams.baopCompletionTime, //报批时间
				releaseTime: props.requestParams.releaseTime, //发布时间
				implementationTime: props.requestParams.implementationTime, //实施时间
				progressCode: 'OutlinePreparation',
				routeName: '/bianzhi/shenhe/index',
				filesRecordList: uploadedFiles.value, //所有附件
				mainUnitList: [], //主编单位
				partUnitList: [], //参编单位
				projectMainDrafterList: [] //主要起草人员
			}

			updateProgressApi(data).then(res => {
				emit('updateData', '')
				ElMessage.success('暂存成功')
			})
		} else {
			console.log('error submit!!')
			return false
		}
	})
}

const Emittion = (type: string, code: number) => {
	const experlist = formParams.value.outlinePreparationExperts.map((it: any) => ({
		expertName: it.expertName,
		expertTitle: it.expertTitle,
		expertCompany: it.expertCompany,
		expertTel: it.expertTel,
		id: it.id ? it.id : ''
	}))
	//console.log(experlist, 'fsjfdsjfdjdsj')
	const data = {
		expertsList: experlist,
		id: props.requestParams.id,
		standardProjectName: props.requestParams.name,
		standardNumber: props.requestParams.standardNumber,
		dgbzReviewTime: props.requestParams.dgbzReviewTime, //大纲评审时间  //大纲评审时间
		zqyjReviewTime: props.requestParams.zqyjReviewTime, //征求意见评审时间
		songsReviewTime: props.requestParams.songsReviewTime, //送审评审时间
		baopCompletionTime: props.requestParams.baopCompletionTime, //报批时间
		releaseTime: props.requestParams.releaseTime, //发布时间
		implementationTime: props.requestParams.implementationTime, //实施时间
		progressCode: type,
		progressStatus: code,
		routeName: '/bianzhi/shenhe/index',
		filesRecordList: uploadedFiles.value, //所有附件
		mainUnitList: [], //主编单位
		partUnitList: [], //参编单位
		projectMainDrafterList: [] //主要起草人员
	}

	updateStageAndStatusApi(data).then(res => {
		// nextTick(() => {
		// 	router.push({
		// 		path: '/bianzhi/shenbao/index'
		// 	})
		// })
		emit('updateData', '')
		ElMessage.success('提交成功')
	})
}

const cancelSubmit = () => {
	ElMessageBox.confirm('是否确认退回', '确认退回', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			const data = {
				id: props.requestParams.id,
				progressStage: 6,
				progressStatus: 0
			}
			changeStageAndStatusApi(data).then(res => {
				emit('updateData', '')
				ElMessage.success('退回成功')
			})
		})
		.catch(() => {})
}
</script>

<style lang="scss" scoped>
.card-header-box1 {
	display: flex;

	flex-direction: column;

	overflow-y: scroll;
	height: 100%;

	&::-webkit-scrollbar {
		display: none;
	}

	.titlezi {
		font-size: 16px;
		color: #333;
	}

	.kuaibj {
		background-color: #f5f6fa;
		padding: 20px;
		border-radius: 6px;
	}

	.fjsmzi {
		font-size: 12px;
		color: #606266;
		margin-left: 5px;
	}
}
</style>
